package com.rockymew.core.mybatis.paging.utils;

public class SqlUtil {

    public static String sqlToCountSql( String sql ){
        //将关键字 SELECT FROM ORDER BY 转换为大写
        sql = sql.replaceAll("(?i)([\\(\\s]|^)SELECT\\s", "$1 SELECT ");
        sql = sql.replaceAll("(?i)\\sFROM\\s", " FROM ");
        sql = sql.replaceAll("(?i)\\sORDER\\s+BY " , " ORDER BY ");

        //将最外层SELECT * FROM转换为SELECT COUNT(*) FROM
        int select = sql.indexOf( " SELECT " );
        int from   = sql.indexOf(" FROM ");

        StringBuffer buffer = new StringBuffer();
        buffer.append( sql.substring(0, select + 1) );
        buffer.append( " SELECT COUNT(*) " );
        buffer.append( sql.substring(from+1) );

        sql = buffer.toString();

        //删除最外层SELECT 的 ORDER BY语句
        int orderby = sql.lastIndexOf(" ORDER BY ");

        if( orderby != -1 ){
            int quoteL = 0;
            int quoteR = 0;
            for (int i = orderby+1; i < sql.length(); i++) {
                if( sql.charAt(i) == '(' ){
                    quoteL++;
                }else if( sql.charAt(i) == ')' ){
                    quoteR++;
                }
            }
            if( quoteL == quoteR ){
                sql = sql.substring(0, orderby + 1);
            }
        }
        return sql;
    }
}
